package com.shoppingmall.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.shoppingmall.mapper.UserMapper;
import com.shoppingmall.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetialServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userMapper.getUserByName(username);
        System.out.println(username);
        if (userInfo == null) {
            System.out.println("用户名不存在...");
            throw new UsernameNotFoundException("用户名不存在...");
        }
        if (userInfo.getUser_status() == -1) {//用户被冻结
            System.out.println("用户被冻结....");
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        String password = userInfo.getUser_password();
        userInfo.setUser_password(null);
        User user = new User(
                JSONObject.toJSONString(userInfo),
                password,
                true,
                true,
                true,
                userInfo.getUser_status() == 0 ? true : false,
                authorities
        );
        return user;
    }
}
